from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from backend.schemas.alert import AlertCreate, AlertUpdate, AlertResponse
from backend.db.models import Alert
from backend.db.database import get_db

router = APIRouter(prefix="/api/alerts", tags=["alerts"])


# 1. 创建提醒
@router.post("/", response_model=AlertResponse)
def create_alert(alert: AlertCreate, db: Session = Depends(get_db)):
    db_alert = Alert(
        title=alert.title,
        content=alert.content,
        alert_time=alert.alert_time,
        repeat=alert.repeat
    )
    db.add(db_alert)
    db.commit()
    db.refresh(db_alert)
    return db_alert


# 2. 获取所有提醒
@router.get("/", response_model=List[AlertResponse])
def get_alerts(is_active: bool = None, db: Session = Depends(get_db)):
    query = db.query(Alert)
    if is_active is not None:
        query = query.filter(Alert.is_active == is_active)
    return query.order_by(Alert.alert_time).all()


# 3. 获取单个提醒
@router.get("/{alert_id}", response_model=AlertResponse)
def get_alert(alert_id: int, db: Session = Depends(get_db)):
    alert = db.query(Alert).filter(Alert.id == alert_id).first()
    if not alert:
        raise HTTPException(status_code=404, detail="提醒不存在")
    return alert


# 4. 更新提醒
@router.put("/{alert_id}", response_model=AlertResponse)
def update_alert(
        alert_id: int,
        alert_update: AlertUpdate,
        db: Session = Depends(get_db)
):
    alert = db.query(Alert).filter(Alert.id == alert_id).first()
    if not alert:
        raise HTTPException(status_code=404, detail="提醒不存在")

    # 更新字段（只更新传入的非空字段）
    if alert_update.title:
        alert.title = alert_update.title
    if alert_update.content:
        alert.content = alert_update.content
    if alert_update.is_active is not None:
        alert.is_active = alert_update.is_active

    db.commit()
    db.refresh(alert)
    return alert


# 5. 删除提醒
@router.delete("/{alert_id}")
def delete_alert(alert_id: int, db: Session = Depends(get_db)):
    alert = db.query(Alert).filter(Alert.id == alert_id).first()
    if not alert:
        raise HTTPException(status_code=404, detail="提醒不存在")

    db.delete(alert)
    db.commit()
    return {"message": "提醒已删除"}